# -*- coding: utf-8 -*-
import math


# 两种推荐，向用户推荐任务，向任务推荐用户
# 实现用户协同过滤算法进行系统推荐
class UserSimilarity:

    # taskJoin = [
    #     'firstpeople': ['task1', 'task2', 'task3'],
    #     'secondpeople': ['task2', 'task3'],
    #     'thirdpeople': ['task3', 'task1', 'task4'],
    #     'fourthpeople': ['task2', 'task4'],
    # ]
    # userTask = ['task2', 'task3']
    # 向用户推荐任务,计算用户相似度，然后读取任务列表推荐尚未结束并且没有加入的任务
    def UserSimilarity(self):
        taskJoin = {
            'firstpeople': ['task1', 'task2', 'task3'],
            'secondpeople': ['task2', 'task3'],
            'thirdpeople': ['task3', 'task1', 'task4'],
            'fourthpeople': ['task2', 'task4'],
        }
        userTask = ['task2', 'task3']
        userList = self.UserSimilarity(taskJoin, userTask)
        topList = self.getSimilarityTask(userList, taskJoin, userTask)
        print topList

    # 想任务推荐用户，计算相似任务，然后读取任务列表得到推荐的用户
    def TaskSimilarity(self):
        pass

    # 计算用户的余弦相似度,得到相似用户排序
    def userSimilarity(self, taskJoin, userTask):
        userWeight = {}
        for join in taskJoin:
            similar = self.countSimilary(taskJoin[join], userTask)
            similar = (similar + 0.0) / math.sqrt(len(taskJoin[join]) * len(userTask) * 1.0)
            print similar
            userWeight[join] = similar
        print userWeight
        userWeight.sort()
        return userWeight

    # 计算用户相同的元素
    def countSimilary(self, upList, downList):
        itemList = [x for x in upList if x in downList]
        return len(itemList)

    # 根据相似的用户得到推荐的任务
    def getSimilarityTask(self, userList, taskJoin, userTask):
        returnList = []
        for user in userList:
            taskList = taskJoin[user]
            taskList = [x for x in taskList if x not in userTask]
            returnList.append(taskList)
        return returnList
